using System.Text;
using LDNS.Interfaces;
using LDNS.Models;
using LDNS.SDK.Commands.Models;
using LDNS.Utilities;

namespace LDNS.Commands
{
    /// <summary>
    /// 获取统计信息命令处理器
    /// 处理GET_STATISTICS命令，获取DNS服务统计信息
    /// 作者：huobing
    /// </summary>
    public class GetStatisticsCommandHandler : CommandHandlerBase<GetStatisticsCommand, GetStatisticsResult>
    {
        private readonly IDnsService _dnsService;
        
        /// <summary>
        /// 命令名称
        /// </summary>
        public override string CommandName => GetStatisticsCommand.NAME;
        
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dnsService">DNS服务实例</param>
        public GetStatisticsCommandHandler(IDnsService dnsService)
        {
            _dnsService = dnsService;
        }
        
        /// <summary>
        /// 执行命令
        /// </summary>
        /// <param name="args">命令参数</param>
        /// <returns>执行结果</returns>
        public override BaseCommandResult Execute(string[] args)
        {
            try
            {
                GetStatisticsResult result = CreateSuccessResult();
                // 获取DNS缓存统计信息
                result.DnsCacheCount = DnsCacheManager.Instance.DnsCache.Count;
                // 获取DNS服务统计信息
                DnsStatistics stats = _dnsService.GetDnsStatistics();
                result.TotalQueries = stats.SuccessfulQueries + stats.FailedQueries;
                result.SuccessfulQueries = stats.SuccessfulQueries;
                result.FailedQueries = stats.FailedQueries;
                result.AverageResponseTime = stats.AverageResponseTime;
                
                // 复制查询类型分布
                result.QueryTypeDistribution = new Dictionary<string, long>(stats.QueryTypeDistribution);
                return result;
            }
            catch (System.Exception ex)
            {
                return CreateErrorResult($"获取统计信息失败: {ex.Message}");
            }
        }
    }
}